package nsqserver

import (
	// "bp/cache"
	// "bp/component"
	"bp/conf"
	"bp/db"
	fo "bp/internal/nsqserver/failover"
	bizCancelConsumerOfMall "bp/internal/nsqserver/mall-biz_cancelConsumer"
	orderCancelConsumerOfMall "bp/internal/nsqserver/mall-order_cancelConsumer"
	orderPayFinishConsumerOfPay "bp/internal/nsqserver/pay-order_pay_finishConsumer"
	"bp/internal/nsqserver/producer"
	"bp/internal/service/com"
	"bp/internal/service/entity"
	"go.uber.org/zap"
)

const (
	appID = "bp"
)

var (
	nsqServer *NsqServer
)

type NsqServer struct {
	slog *zap.SugaredLogger
}

// InitNsqServer init all nsq proxies
func InitNsqServer(
	slog *zap.SugaredLogger,
	pgConfPtr *conf.PgSection,
	nsqConfPtr *conf.NsqSection,
	vars *conf.VarsSection,
	// adp *cache.Adapter,
	// clientProxy *client.GrpcClientProxy,
	// cm *component.ComponentManger,
) (err error) {
	slog.Infof("appID:%s", appID)
	if nsqServer == nil {
		nsqServer = &NsqServer{
			slog: slog.With("entry", "nsq"),
		}
		pgdao := db.New(pgConfPtr, slog)
		pub, err := producer.NewNsqProducerProxy(slog, pgdao, nsqConfPtr)
		if err != nil {
			slog.Errorf("pub start failed, %s", err.Error())
		}
		entityHub := entity.NewEntityHub(slog, pgdao, vars)
		comHub := com.NewComHubForNsq(slog, pgdao, vars, pub, entityHub)
		failover := fo.New(slog, pgdao, vars)

		_, err = bizCancelConsumerOfMall.New(nsqConfPtr, slog, pgdao, vars, failover, entityHub, comHub)
		if err != nil {
			slog.Fatalf("failed to init bizCancelConsumerOfMall: %s", err.Error())
		}

		_, err = orderCancelConsumerOfMall.New(nsqConfPtr, slog, pgdao, vars, failover, entityHub, comHub)
		if err != nil {
			slog.Fatalf("failed to init orderCancelConsumerOfMall: %s", err.Error())
		}

		_, err = orderPayFinishConsumerOfPay.New(nsqConfPtr, slog, pgdao, vars, failover, entityHub, comHub)
		if err != nil {
			slog.Fatalf("failed to init orderPayFinishConsumerOfPay: %s", err.Error())
		}

		slog.Info("nsq started")
	} else {
		slog.Info("nsq already started")
	}

	return
}
